﻿using System;
using System.IO;
using System.Text;

namespace XNET.Extension
{
    /// <summary>
    /// 字符流扩展
    /// </summary>
    public static class StreamExtensions
    {
        /// <summary>
        /// 将字符流转换为字节数组
        /// </summary>
        /// <param name="Input">字符流</param>
        /// <returns></returns>
        public static byte[] ReadAllBinary(this Stream Input)
        {
            var TempInput = Input as MemoryStream;
            if (TempInput != null)
            {
                return TempInput.ToArray();
            }
            var Buffer = new byte[1024];
            var ReturnValue = (byte[])null;
            using (var Temp = new MemoryStream())
            {
                while (true)
                {
                    var Count = Input.Read(Buffer, 0, Buffer.Length);
                    if (Count <= 0)
                    {
                        ReturnValue = Temp.ToArray();
                        break;
                    }
                    Temp.Write(Buffer, 0, Count);
                }
            }
            return ReturnValue;
        }

        /// <summary>
        /// 将字符流转换为字符串
        /// </summary>
        /// <param name="Input">字符流</param>
        /// <param name="EncodingUsing">字符编码 (默认 UTF8)</param>
        /// <returns></returns>
        public static string ReadAll(this Stream Input, Encoding EncodingUsing = null)
        {
            return Input.ReadAllBinary().ToString(EncodingUsing);
        }
    }
}
